<?php

function reequipment_adminapi_createequipment($args)
{
    extract($args);

    // Argument check - make sure that all required arguments are present,
    // if not then set an appropriate error message and return
    $invalid = array();
   	if (!isset($model_id) || !is_int($model_id)) {
        $invalid[] = 'model_id';
    } 
   	if (!isset($cycles) || !is_int($cycles)) {
        $invalid[] = 'cycles';
    }     
    if (!isset($serial_number) || !is_string($serial_number)) {
        $invalid[] = 'serial_number';
    } 
    if (!isset($voltage) || !is_string($voltage)) {
        $invalid[] = 'voltage';
    } 
    if (!isset($machine_name) || !is_string($machine_name)) {
        $invalid[] = 'machine_name';
    } 
    if (count($invalid) > 0) {
        $msg = xarML('Invalid #(1)', join(', ', $invalid));
        xarErrorSet(XAR_SYSTEM_EXCEPTION, 'BAD_PARAM', new SystemException($msg));
        return;
    } 
    
    // First get the company id if not specified.  It would be specified if the user is assigned to multiple companies.
    $company_user_id = xarSessionGetVar('uid');    
    if (empty($company_id)){
    	$company = xarModAPIFunc('reequipment', 'user', 'getrel', array('user_id' => $company_user_id));
		foreach($company as $var){
			$company_id = $var['company_id'];
		}
	}
            
    if (empty($area_id)){
    	$area = xarModAPIFunc('reequipment', 'user', 'getmodels', array('model_id' => $model_id));
		foreach($area as $var){
			$area_id = $var['area_id'];
		}
	}
	
	// return $area_id;
    // Get datbase setup
    $dbconn =& xarDBGetConn();
    $xartable =& xarDBGetTables();
    $table = $xartable['reequipment'];
    // Get next ID in table
    $nextId = $dbconn->GenId($table);

    // Add item
    $query = "INSERT INTO $table ("
        . " equipment_id, model_id, area_id, company_id, serial_number, machine_name, voltage, cycles )"
        . " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $result =& $dbconn->Execute($query, array($nextId, $model_id, $area_id, $company_id, $serial_number, $machine_name, $voltage, $cycles));
    if (!$result) return;
    // Get the ID of the item that we inserted
    $id = $dbconn->PO_Insert_ID($table, 'equipment_id');

    // Let any hooks know that we have created a new forum
    $args['module'] = 'reequipment';
    $args['itemtype'] = 4; // post
    $args['itemid'] = $id; // post
    xarModCallHooks('item', 'create', $id, $args);// post
    // Return the id of the newly created link to the calling process
    return $id;
}
?>